package com.enation.app.web.tag;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.enation.app.web.core.model.VisitorWebSite;
import com.enation.app.web.core.service.impl.VisitorWebSiteManager;
import com.enation.framework.context.webcontext.ThreadContextHolder;
import com.enation.framework.taglib.BaseFreeMarkerTag;
import com.enation.framework.util.DateUtil;

import freemarker.template.TemplateModelException;

/**
 * 
 * @function 访问量标签
 * @author 小韦
 * @time 2016年12月10日 下午9:48:29
 */
@Component
public class VisitorWebsite extends BaseFreeMarkerTag {

	@Autowired
	private VisitorWebSiteManager visitorWebSiteManager;

	@Override
	protected Object exec(Map params) throws TemplateModelException {

		// 获取当天的visitor
		Date date = new Date();
		String time = DateUtil.toDay(date);
		VisitorWebSite visitorWebSite = visitorWebSiteManager
				.getVisitorBytime(time);

		HttpServletRequest request = ThreadContextHolder.getHttpRequest();

		ServletContext context = request.getServletContext();
		Integer num = (Integer) context.getAttribute("num");

		if (num == null) {
			num = 0;
		}

		// 判断是否为空
		if (visitorWebSite == null) {
			// 判断间隔日期
			VisitorWebSite v1 = visitorWebSiteManager.getVisitorOne();
			Date time1 = DateUtil.toDate(time, "yyyy-MM-dd");
			Date time2 = DateUtil.toDate(v1.getTime(), "yyyy-MM-dd");
			long diff = time1.getTime() - time2.getTime();
			int day = (int) (diff / 86400000);
			if (day > 1) {
				for (int i = 1; i <= day - 1; i++) {
					Calendar calendar = new GregorianCalendar();
					calendar.setTime(time2);
					calendar.add(calendar.DATE, 1);
					time2 = calendar.getTime();

					String strtime = DateUtil.toDay(time2);
					VisitorWebSite addSite = new VisitorWebSite();
					addSite.setPageview(0);
					addSite.setVisitor(0);
					addSite.setTime(strtime);
					visitorWebSiteManager.insertVisitor(addSite);
				}
			}

			num = num - 1;
			context.setAttribute("num", num);

			// 创建一个visitor
			VisitorWebSite temp = new VisitorWebSite();
			temp.setPageview(1);
			temp.setVisitor(1);
			temp.setTime(time);
			visitorWebSiteManager.insertVisitor(temp);
		} else {
			visitorWebSite.setPageview(visitorWebSite.getPageview() + 1);
			visitorWebSite.setVisitor(visitorWebSite.getVisitor() + num);
			num = 0;
			context.setAttribute("num", num);

			visitorWebSiteManager.updateVisitor(visitorWebSite);

		}

		return "";
	}

}
